//////////////////////////////////////////////////////////////////////
//
//	Copyright 2010-2011 Rogo's Team. All Rights Reserved
//
//////////////////////////////////////////////////////////////////////
package com.rogo.weibo.core
{
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;

	/**
	 * Weibo API Super Class 
	 * 
	 * @author rogo
	 * 
	 */	
	public class DoAPI
	{
		public function DoAPI(dataHandler:Function, errorHandler:Function)
		{
			_dataHandler = dataHandler;
			_errorHandler = errorHandler;
		}
		
		//--------------------------------------------------------------------------
		//
		//  Variables
		//
		//--------------------------------------------------------------------------
		
		protected var _dataHandler:Function;
		protected var _errorHandler:Function;
		
		//--------------------------------------------------------------------------
		//
		//  Methods
		//
		//--------------------------------------------------------------------------
		
		protected function send(url:String, 
								resultHandler:Function = null,
							    errorHandler:Function = null,
								method:String = URLRequestMethod.GET, 
								params:String = null):void
		{
			var urlRequest:URLRequest = new URLRequest(url);
			urlRequest.method = method;
			
			if(method == URLRequestMethod.POST){
				var vars:URLVariables = new URLVariables(params);
				urlRequest.data = vars;
			}
			
			var urlLoader:URLLoader = new URLLoader();
			urlLoader.addEventListener(Event.COMPLETE, urlLoader_completeHandler);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, urlLoader_ioErrorHandler);
			urlLoader.load(urlRequest);
			
			function urlLoader_completeHandler(e:Event):void
			{
				var currentTarget:IEventDispatcher = e.currentTarget as IEventDispatcher;
				if (currentTarget && currentTarget.hasEventListener(Event.COMPLETE))
					currentTarget.removeEventListener(Event.COMPLETE, urlLoader_completeHandler);
				
				if (resultHandler != null)
					resultHandler(e.currentTarget.data);
			}
			
			function urlLoader_ioErrorHandler(e:IOErrorEvent):void
			{
				var currentTarget:IEventDispatcher = e.currentTarget as IEventDispatcher;
				if (currentTarget && currentTarget.hasEventListener(IOErrorEvent.IO_ERROR))
					currentTarget.removeEventListener(IOErrorEvent.IO_ERROR, urlLoader_ioErrorHandler);
				
				if (errorHandler != null)
					errorHandler(e.currentTarget.data);
			}
		}
		
	}
}